//
//  TiDanListVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2020/9/11.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "TiDanListVC.h"
#import "TiDanMainModel.h"
#import "TiDanListCell.h"
#import "TiDanDetailVC.h"

@interface TiDanListVC ()<UITableViewDelegate,UITableViewDataSource> {
    int page;
}

@property (nonatomic, strong) NSMutableArray <TiDanMainModel *>*array;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation TiDanListVC

-(UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, self.is_accept == 2 ? 40 : 0)];
        _topView.backgroundColor = Color_backgroundColor;
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(15, 10, ScreenW - 30, 30)];
        btn.backgroundColor = HexColorA(0xFBA962, 0.1);
        btn.layer.masksToBounds = YES;
        btn.layer.cornerRadius = 4;
        [btn setTitle:@"显示调度车辆的为3PL直接调度，否则需要您自行调度提货车辆" forState:0];
        [btn setTitleColor:HexColor(0xFBA962) forState:0];
        btn.titleLabel.font = [UIFont systemFontOfSize:12];
        btn.userInteractionEnabled = NO;
        [_topView addSubview:btn];
    }
    return _topView;
}

-(NSMutableArray<TiDanMainModel *> *)array {
    if (!_array) {
        _array = [NSMutableArray array];
    }
    return _array;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.topView.nim_bottom, ScreenW, ScreenH - BottomHeight - NaviHeight - 40 - self.topView.nim_height) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        __weak_self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            __strong_self;
            strongSelf->page = 1;
            [strongSelf requestForList];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            __strong_self;
            strongSelf->page++;
            [strongSelf requestForList];
        }];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    page = 1;
    [self.view addSubview:self.topView];
    [self.view addSubview:self.tableView];
    [self requestForList];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshList) name:ReceiptDeliveryRefreshTiDanShouLiList object:nil];
    if (self.is_accept == 2) {
        [self stopTimer];
        [self startTimer];
    }
}

//开启定时器
-(void)startTimer {
     if (!self.timer) {
          self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                        target:self
                                                      selector:@selector(timerLoop)
                                                      userInfo:nil
                                                       repeats:YES];
          [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
     }
}

//停止定时器
-(void)stopTimer {
     if (self.timer) {
          [self.timer invalidate];
          self.timer = nil;
     }
}
//计时
-(void)timerLoop {
    [self.array enumerateObjectsUsingBlock:^(TiDanMainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.downtime > 0) {
            obj.downtime -= 1;
            TiDanListCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
            [cell configWithTime:obj.downtime];
        }
    }];
}

- (void)refreshList {
    page = 1;
    [self requestForList];
}

- (void)requestForList {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@(self.is_accept) forKey:@"is_accept"];
    [dic setObject:@(page) forKey:@"page"];
    [HttpRequest PostWithApi:LogisticsSupplierTiDanManagerList params:dic progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            if (self->page == 1) {
                [self.array removeAllObjects];
                self.array = [TiDanMainModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
            }else {
                NSArray *array = [TiDanMainModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
                [self.array addObjectsFromArray:array];
            }
            BOOL has_more = [responseObject[@"has_more"] boolValue];
            if (has_more) {
                self.tableView.mj_footer.hidden = NO;
            }else {
                self.tableView.mj_footer.hidden = YES;
            }
            [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } fail:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TiDanListCell *cell = [TiDanListCell TiDanListCellWithTableView:tableView];
    TiDanMainModel *model = self.array[indexPath.row];
    cell.model = model;
    __weak_self;
    cell.jieDanBlock = ^{
        TiDanDetailVC *vc = [TiDanDetailVC new];
        vc.sdl_id = model.sdl_id;
        vc.sdlv_id = model.sdlv_id;
        vc.dispatch = model.dispatch;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    cell.refreshBlock = ^{
        [weakself refreshList];
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    TiDanListCell *cell = [TiDanListCell TiDanListCellWithTableView:tableView];
    cell.model = self.array[indexPath.row];
    return cell.height;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TiDanDetailVC *vc = [TiDanDetailVC new];
    TiDanMainModel *model = self.array[indexPath.row];
    vc.sdl_id = model.sdl_id;
    vc.sdlv_id = model.sdlv_id;
    vc.dispatch = model.dispatch;
    [self.rt_navigationController pushViewController:vc animated:YES];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = Color_backgroundColor;
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self stopTimer];
}

@end
